package com.hospital.ecard.patienthandler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hospital.api.RemoteDictionaryService;
import com.hospital.common.core.module.controller.vo.PatientReqEntity;
import com.hospital.common.core.module.entity.BankMedicalCardDict;
import com.hospital.common.core.utils.AgeUtil;
import com.hospital.common.core.utils.SpringContextHolder;
import com.hospital.ecard.module.entity.PatientInfo;
import com.hospital.ecard.module.service.PatientInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lvyao
 * @description 新建患者信息
 * @date 2021/5/6
 */
@Slf4j
public class PatientInfoNewHandler implements PatientInfoElectronicHandler {
    private PatientInfoService patientInfoService= SpringContextHolder.getBean(PatientInfoService.class);

    private RemoteDictionaryService remoteDictionaryService= SpringContextHolder.getBean(RemoteDictionaryService.class);

    @Override
    public PatientInfo patientHandleInfo(PatientReqEntity patientReqEntity) throws Exception {
        PatientInfo patientInfo = new PatientInfo();
        if (patientReqEntity.getHealthCardId() == null){
            throw new RuntimeException("新建患者信息必须填写HealthCardId");
        }
        patientInfo = getNewPatientOld(patientReqEntity);
        if (patientInfo != null && patientInfo.getPatientId() != null){
            boolean isCheck = patientReqEntity.getCreateChannel()!=null&&patientReqEntity.getCreateChannel().equals("1")?true:false;
            if (!isCheck && !patientInfo.getName().trim().equals(patientReqEntity.getPatientName().trim())){
                String errormsg = "根据患者ID或实体卡号获取患者姓名为{" + patientInfo.getName().trim() + "}与填写姓名{" + patientReqEntity.getPatientName().trim() + "}不符，请前往窗口核实信息！";
                throw new RuntimeException(errormsg);
            }
            if (patientInfo.getIdNo() != null && !patientReqEntity.getIdNo().trim().toUpperCase().equals(patientInfo.getIdNo().trim().toUpperCase())){
                String errormsg = "根据患者ID或实体卡号获取患者身份证号为{" + patientInfo.getIdNo().trim().toUpperCase() + "}与填写身份证{" + patientReqEntity.getIdNo().trim().toUpperCase() + "}不符，请前往窗口核实信息！";
                throw new RuntimeException(errormsg);
            }
            patientReqEntity.setDataOper(0);
            return patientInfo;
        }
        BeanUtils.copyProperties(patientReqEntity, patientInfo);
        patientInfo.setIdNo(patientReqEntity.getIdNo().toUpperCase());
        patientInfo.setName(patientReqEntity.getPatientName());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String s = sdf.format(patientReqEntity.getBirthDay());
        patientInfo.setDateOfBirth(sdf.parse(s));
        patientInfo.setPhoneNumberHome(patientReqEntity.getPhone());
        if ("1,3".contains(patientReqEntity.getCreateChannel()) && patientReqEntity.getTerminal() != null && !patientReqEntity.getTerminal().equals("")) {
            if ("3".equals(patientReqEntity.getCreateChannel())) {
                QueryWrapper<BankMedicalCardDict> entityWrapper = new QueryWrapper<>();
                entityWrapper.eq("terminal", patientReqEntity.getTerminal());
                 BankMedicalCardDict bankMedicalCardDict = remoteDictionaryService.getbankMedicalCardDictList().stream().filter(bank -> bank.getTerminal().equals(patientReqEntity.getTerminal())).findFirst().orElse(null);
                if (bankMedicalCardDict != null) {
                    patientInfo.setOperator(bankMedicalCardDict.getUserId());
                    int maxPid = Integer.parseInt(bankMedicalCardDict.getMaxPatientId()) + 1;
                    String patientId = bankMedicalCardDict.getBankMachineCode() + String.format("%06d", maxPid);
                    patientInfo.setPatientId(patientId);
                    bankMedicalCardDict.setMaxPatientId(String.format("%06d", maxPid));
                    remoteDictionaryService.updateDtoMedicalCardDictUpdate(bankMedicalCardDict);
                } else {
                    throw new RuntimeException("自助机配置表中未找到该设备配置信息");
                }
            } else {
                patientInfo.setOperator(patientReqEntity.getTerminal());
            }
        } else {
            patientInfo.setOperator("9271");
        }
        if (patientInfo.getPatientId() == null) {
            String patientId = patientInfoService.getPatientId();
            if (patientId != null) {
                patientInfo.setPatientId(patientId);
            } else {
                throw new RuntimeException("获取patientId失败");
            }
        }
        int age = AgeUtil.getAgeByBirth(patientReqEntity.getBirthDay());
        if (age >= 65) {
            patientInfo.setChargeType("寿星优惠");
        }
        patientInfo.setMailingAddress(patientReqEntity.getAddress());
        patientInfo.setBirthPlace(patientReqEntity.getIdNo().substring(0, 6));
        patientReqEntity.setDataOper(1);
        return patientInfo;
    }


    /**
     * 新建患者信息前先看是否有用身份证件注册过的信息
     * @param patientReqEntity
     * @return
     */
    public  PatientInfo getNewPatientOld(PatientReqEntity patientReqEntity){
        PatientInfo patientInfo = new PatientInfo();
        List<PatientInfo> patientInfoList = patientInfoService.selectPatientInfoByIdNo(patientReqEntity.getIdNo());
        if (patientInfoList != null && patientInfoList.size() >0 ){
            String healthCardId = patientReqEntity.getHealthCardId();
            List<PatientInfo> patientInfoListHealth = patientInfoList.stream().filter(c -> c.getHealthCardId() !=null && c.getHealthCardId().equals(healthCardId)).collect(Collectors.toList());
            if (patientInfoListHealth != null && patientInfoListHealth.size() >0){
                patientInfo = patientInfoListHealth.get(0);
            }else {
                patientInfo = patientInfoList.get(0);
            }
        }
        return patientInfo;
    }
}
